package com.fm.common.net.baseCoroutine

import com.fm.common.net.baseCoroutine.exception.UncaughtCoroutineExceptionHandler
import com.ticket.rccl.net.baseCoroutine.listener.CoroutineErrorListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import java.io.Closeable
import kotlin.coroutines.CoroutineContext

/**
 * @CreateData:     2020/12/22
 * @Author:         lyy
 * @Description:    安全的 CoroutineScope，支持异常处理
 */

class SafeCoroutineScope(context: CoroutineContext, errorHandler: CoroutineErrorListener? = null) : CoroutineScope, Closeable {

    override val coroutineContext: CoroutineContext = SupervisorJob() + context + UncaughtCoroutineExceptionHandler(errorHandler)

    override fun close() {
        coroutineContext.cancelChildren()
    }
}